<template>
	<view>
		<van-address-edit
		  align="left"
		  :area-list="areaList"
		  :show-delete="isDelete"
		  show-set-default
		  show-search-result
		  show-postal
		  :address-info="AddressInfo"
		  :area-columns-placeholder="['请选择', '请选择', '请选择']"
		  @save="onSave"
		  @delete="onDelete"
		/>
	</view>
</template>

<script>
	
	import areaList from '@/utils/area';
	import { selectCustomerAddressById,insertCustomerAddr,updateCustomerAddr,deleteCustomerAddrById } from '@/api/customer/customer.js'
	import { Toast } from "vant";
	
	export default {
		data() {
			return {
				areaList,
					isDelete: true,
					AddressInfo:{
					id:null,
					name:null,
					tel:null,
					province:null,
					city:null,
					county:null,
					addressDetail: null,
					postalCode: null,
					areaCode:null,
					isDefault:null,
					customerAddrId:null,
				}
			}
		},
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			let customerAddrId = parseInt(option.customerAddrId);
			let addressType = option.addressType;
			if(addressType == 1){
				this.isDelete = false
			}else{
				this.isDelete = true
			}
			this.getCustomerAddressById(customerAddrId);
		},
		methods: {
			toBack() {
				//返回上一级页面
				this.$router.go(-1)
			  },
			  getCustomerAddressById(id){
				selectCustomerAddressById(id).then((res) =>{
				  this.AddressInfo.id = res.data.data.customerAddrId;
				  this.AddressInfo.customerAddrId = res.data.data.customerAddrId;
				  this.AddressInfo.name = res.data.data.name;
				  this.AddressInfo.tel = res.data.data.tel;
				  this.AddressInfo.province = res.data.data.province;
				  this.AddressInfo.city = res.data.data.city;
				  this.AddressInfo.county = res.data.data.county;
				  this.AddressInfo.addressDetail = res.data.data.addressDetail;
				  this.AddressInfo.postalCode = res.data.data.postalCode;
				  this.AddressInfo.areaCode = res.data.data.areaCode;
				  if(res.data.data.isDefault == "1"){
					this.AddressInfo.isDefault = true
				  }else{
					this.AddressInfo.isDefault = false
				  }
				})
			  },
			  onSave(res) {
				if(res.id == null){
				  if (res.isDefault == null){
					res.isDefault = "0"
				  }else{
					res.isDefault = "1"
				  }
				  insertCustomerAddr(res).then((res) =>{
					if(res.data.code == 200){
					  Toast({
						message: "添加成功",
						position: "top"
					  });
					  uni.navigateBack()
					}
				  })
				}else{
				  if (res.isDefault == false){
					res.isDefault = "0"
				  }else{
					res.isDefault = "1"
				  }
				  updateCustomerAddr(res).then((res) => {
					if(res.data.code == 200){
					  Toast({
						message: "修改成功",
						position: "top"
					  });
					  uni.navigateBack()
					}
				  })
				}
		
			  },
			  onDelete(res) {
				deleteCustomerAddrById(res.customerAddrId).then((res) =>{
				  Toast({
					message: "删除成功",
					position: "top"
				  });
				  this.$router.go(-1)
				})
			  },
		}
	}
</script>

<style>

</style>
